<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
const route = useRouter();
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Files, Document, Delete, FolderAdd } from '@element-plus/icons-vue'	//导入Search图标
import { animalsSurveypage, workerInfo, exportSurvey, surveyDelete, siteInfo, exportPages, exportDeletes, formInfo, flSurvey } from '@/utils/api.js'
import close from '@/assets/icon/close.svg'

import moment from 'moment';
const $moment = moment;
// 对象
let usermsg = '';
const multipleSelection = ref([]);
const eel = ref([]);
const isdwn = ref(false);
const value1 = ref('');
const fltype = ref('animalsSurvey');
const pageSize = ref(20);
const pageNum = ref(1);
const totalElements = ref(100);
const currentPage = ref(1)

const surveyName = ref('');
const site = ref('');
const formId = ref('');
const works = ref([]);
const sites = ref([]);
const forms = ref([]);

const keywords = ref("");
const date = ref("");
const resourceType = ref("animal");
const list = ref([]);


const delItem = (item) => {
    ElMessageBox.confirm(
        '确定要删除这条数据吗?',
        '消息提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            surveyDelete({
                type: fltype.value,
                surveyIdList: item
            }).then((res) => {
                if (res.code == '200') {
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                    resp();
                } else {
                    ElMessage({
                        type: 'warning',
                        message: res.msg,
                    })
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}



const handleSelectionSelectAll = (val) => {
    let arr = []
    val.forEach(e => {
        arr.push(e.id)
    })
    multipleSelection.value = arr;
}

const handleSelectionSelect = (val) => {
    let arr = []
    val.forEach(e => {
        arr.push(e.id)
    })
    multipleSelection.value = arr;
}



// 获取人员
const getworkerInfo = async () => {
    let params = `?areaId=${usermsg.areaId}&siteIdStr=`;
    let res = await workerInfo(params)
    if (res.code = '200') {
        works.value = res.data;
    }
}

// 获取分站
const getsiteInfo = async () => {
    let params = `?areaId=${usermsg.areaId}`;
    let res = await siteInfo(params)
    if (res.code = '200') {
        sites.value = res.data;
    }
}

// 获取表单
const getsformInfo = async () => {
    let params = `?areaId=${usermsg.areaId}&appType=RES`;
    let res = await formInfo(params)
    if (res.code = '200') {
        forms.value = res.data;
    }
}

// 导出清单
const deldownZip = async (item) => {
    ElMessageBox.confirm(
        '确定要删除这条数据吗?',
        '消息提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            exportDeletes(item.id).then((res) => {
                if (res.code == '200') {
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                    getquadratExport()
                } else {
                    ElMessage({
                        type: 'warning',
                        message: res.msg,
                    })
                }
            })

        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })


}

const getquadratExport = async () => {
    let res = await exportPages(`?pageNum=1&pageSize=9999&areaId=${usermsg.areaId}&type=调查历史`)
    if (res.code == '200') {
        eel.value = res.data.content;
    }
}

const getqExport = async () => {
    let res = await exportSurvey(`?areaId=${usermsg.areaId}&date=${gettime()}&surveyName=${surveyName.value}&site=${site.value}&formId=${formId.value}&keywords=${keywords.value}&resourceType=${fltype.value}`)
    if (res.code == '200') {
        getquadratExport()
    } else {
        ElMessage({
            message: res.message,
            type: 'warning',
        })
        list.value = []
    }
};

const downZip = (item) => {
    // 创建一个下载链接
    let downloadLink = document.createElement('a');
    downloadLink.href = '/api/admin/export/download/' + item.id;
    // downloadLink.download = item.name; // 设置下载文件的名称

    // 将下载链接添加到页面中（这一步可以根据实际情况进行调整）
    document.body.appendChild(downloadLink);

    // 模拟点击下载链接
    downloadLink.click();
}

// 导出清单

// 分页 B

const handleClick = (tab, event) => {
    // if (tab == 'animalsSurvey') {
    //     resourceType.value = 'animal'
    // }
    // if (tab == 'plantsSurvey') {
    //     resourceType.value = 'plant'
    // }
    // if (tab == 'fungusSurvey') {
    //     resourceType.value = 'fungus'
    // }
    // if (tab == 'treesSurvey') {
    //     resourceType.value = 'tree'
    // }
    // if (tab == 'naturalSurvey') {
    //     resourceType.value = 'natural'
    // }


    date.value = '';
    surveyName.value = '';
    site.value = '';
    formId.value = '';
    keywords.value = '';
    pageNum.value = 1;
    currentPage.value = 1;
    getflSurveypage();
}

const getflSurveypage = async () => {
    let res = await flSurvey(fltype.value, `?areaId=${usermsg.areaId}&date=${gettime()}&surveyName=${surveyName.value}&site=${site.value}&formId=${formId.value}&keywords=${keywords.value}&pageNum=${pageNum.value}&pageSize=20`)
    if (res.code == '200') {
        multipleSelection.value = []
        list.value = res.data.content;
        totalElements.value = res.data.totalElements;
    } else {
        ElMessage({
            message: res.message,
            type: 'warning',
        })
        list.value = []
    }
};

const handleCurrentChange = (val) => {
    pageNum.value = val;
    getflSurveypage();
};

const resp = () => {
    pageNum.value = 1;
    currentPage.value = 1;
    getflSurveypage();
}

// 分页 E
const godetails = (data) => {
    let hisanimal = {
        "pageNum": pageNum.value,
        "keywords": keywords.value,
        "time": date.value,
        "currentPage": currentPage.value,
        "surveyName": surveyName.value,
        "site": site.value,
        "formId": formId.value,
        "fltype": fltype.value
    }
    window.sessionStorage.setItem('hisanimal', JSON.stringify(hisanimal));

    route.push({ path: '/history/animal/animaldetails', query: { fltype: fltype.value, id: data.id } });
};

const gettime = () => {
    let time = '';
    if (date.value && date.value != '') {
        let y = date.value.getFullYear();
        let m = (date.value.getMonth() + 1) > 9 ? (date.value.getMonth() + 1) : '0' + (date.value.getMonth() + 1);
        let d = date.value.getDate() > 9 ? date.value.getDate() : '0' + date.value.getDate();
        time = y + '-' + m + '-' + d;
    } else {
        time = '';
    };

    return time
}

defineExpose({
    $moment
})

onMounted(() => {
    usermsg = window.sessionStorage.getItem('usermsg');
    if (usermsg == undefined) {
        alert('您无权查看该网站，请登录后才能正常使用')
    } else {
        usermsg = JSON.parse(usermsg);
    };

    if (window.sessionStorage.getItem('hisanimal')) {
        let data = JSON.parse(window.sessionStorage.getItem('hisanimal'));
        pageNum.value = data.pageNum;
        keywords.value = data.keywords;
        if (data.time && data.time != '') {
            date.value = new Date(data.time)
        } else {
            date.value = ''
        }
        currentPage.value = data.currentPage;
        surveyName.value = data.surveyName;
        site.value = data.site;
        formId.value = data.formId;
        fltype.value = data.fltype;
        getflSurveypage();
        window.sessionStorage.removeItem('hisanimal')
    } else {
        getflSurveypage();
    }

    getworkerInfo();
    getsiteInfo();
    getsformInfo();
    getquadratExport();

})
</script>
<template>
    <div>
        <div class="ha-title" style="margin-bottom: 16px;">
            <div>
                <span>样点调查</span>
            </div>
            <div style="display: flex;">
                <el-button :icon="FolderAdd" plain @click="getqExport">导出</el-button>
                <el-badge
                    style="margin:0 10px;display: flex;align-items: center;font-family: 'Microsoft YaHei', sans-serif;"
                    :value="eel.length" type="primary">
                    <el-button type="info" @click="getquadratExport(); isdwn = true" plain :icon="Files">
                        导出清单
                    </el-button></el-badge>
                <el-button :icon="Delete" @click="delItem(multipleSelection)" plain>删除({{ multipleSelection.length
                    }})</el-button>
            </div>
        </div>

        <el-tabs v-model="fltype" class="demo-tabs" @tab-change="handleClick">
            <el-tab-pane name="animalsSurvey" label="动物调查">动物调查</el-tab-pane>
            <el-tab-pane name="plantsSurvey" label="植物调查">植物调查</el-tab-pane>
            <el-tab-pane name="fungusSurvey" label="真菌调查">真菌调查</el-tab-pane>
            <el-tab-pane name="treesSurvey" label="古树名木调查">古树名木调查</el-tab-pane>
            <el-tab-pane name="naturalSurvey" label="自然资源调查">自然资源调查</el-tab-pane>
        </el-tabs>


        <el-row :gutter="10">
            <el-col :span="3">
                <el-date-picker v-model="date" @change="resp()" type="date" style="width: 100%;" placeholder="调查时间"
                    size="large" />
            </el-col>
            <el-col :span="3">
                <el-select v-model="site" class="m-2" style="width: 100%;" clearable @change="resp()" placeholder="分站"
                    size="large">
                    <el-option v-for="(item, index) in sites" :key="item.id" :label="item.name" :value="item.id" />

                </el-select>
            </el-col>
            <el-col :span="3">
                <el-select v-model="surveyName" class="m-2" style="width: 100%;" clearable @change="resp()" filterable
                    placeholder="调查人员" size="large">
                    <el-option v-for="(item, index) in works" :key="item.mobile" :label="item.zhName"
                        :value="item.zhName" />
                </el-select>
            </el-col>
            <el-col :span="3">
                <el-select v-model="formId" class="m-2" style="width: 100%;" clearable @change="resp()"
                    placeholder="表单名称" size="large">
                    <el-option v-for="(item, index) in forms" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-col>
            <el-col :span="7"></el-col>
            <el-col :span="5">
                <el-input v-model="keywords" placeholder="搜索物种名称" size="large" class="input-with-select">
                    <template #append>
                        <el-button @click.stop="resp()" :icon="Search" />
                    </template>
                </el-input>
            </el-col>
        </el-row>

        <el-table :data="list" style="width: 100%;height: calc(100% - 190px);" @select-all="handleSelectionSelectAll"
            @select="handleSelectionSelect" :row-style="{ height: '50px' }"
            :header-cell-style="{ 'color': '#333', 'line-height': '40px' }">
            <el-table-column type="selection" width="35" />
            <el-table-column label="分站">
                <template #default="scope">
                    <el-button type="primary" circle style="font-weight: 700;">{{ scope.row.siteStr ?
                        scope.row.siteStr.charAt(0) : '-'
                        }}</el-button>
                    <span style="margin-left: 12px;">{{ scope.row.siteStr }}</span>
                </template>
            </el-table-column>
            <el-table-column label="物种" prop="keywords" />
            <el-table-column label="调查人员" prop="workUser" />
            <el-table-column label="表单名称" prop="formName" />
            <el-table-column label="调查时间" prop="recordTime" />


            <el-table-column label="操作" fixed="right" width="240">
                <template #default="scope">
                    <el-button type="info" @click.stop="godetails(scope.row)" :icon="Document" plain size="small">
                        详情
                    </el-button>
                    <el-button type="info" plain :icon="Delete" @click.stop="delItem([scope.row.id])" size="small">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 B-->
        <div class="ml-page">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" background
                layout="total, prev, pager, next, jumper" :total="totalElements"
                @current-change="handleCurrentChange" />
        </div>
        <!-- 分页 E-->


        <div class="comm-frm" v-if="isdwn">
            <div class="comm-label" style="width: 700px;">
                <div class="comm-close" @click.stop="isdwn = false">
                    <img :src="close" alt="">
                </div>
                <div class="qzTitle">
                    <div></div>
                    <span>导出清单</span>
                </div>
                <br>
                <el-table :data="eel" height="600" style="width: 100%;" :row-style="{ height: '50px' }"
                    :header-cell-style="{ 'color': '#333', 'line-height': '40px' }">

                    <el-table-column label="样方编号" prop="recordNumber" width="200" show-overflow-tooltip />

                    <el-table-column label="生成时间">
                        <template #default="scope">
                            <span>{{ $moment(scope.row.createTime).format('YYYY-MM-DD') }}</span>
                        </template>

                    </el-table-column>
                    <el-table-column label="状态" prop="state">

                        <template #default="scope">
                            <el-button v-if="scope.row.state == '生成中'"
                                style="background-color:rgba(255, 195, 0, 0.1);border:none; color: #FFC300;">
                                {{ scope.row.state }}
                            </el-button>
                            <el-button v-else
                                style="background-color:rgba(56, 123, 255, 0.1);color:var(--wls-color);border:none;">
                                {{ scope.row.state }}
                            </el-button>
                        </template>

                    </el-table-column>
                    <el-table-column label="操作" fixed="right">
                        <template #default="scope">
                            <el-button type="info" :disabled="scope.row.state == '生成中'" @click.stop="downZip(scope.row)"
                                :icon="Document" plain size="small">
                                下载
                            </el-button>
                            <el-button type="info" @click.stop="deldownZip(scope.row)" plain :icon="Delete"
                                size="small">
                                删除
                            </el-button>

                        </template>
                    </el-table-column>
                </el-table>

            </div>
        </div>
    </div>
</template>
<style scoped>
.comm-frm {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 9;
    background-color: rgba(0, 0, 0, .5);
}

.comm-label {
    width: 500px;
    padding: 24px;
    border-radius: 4px;
    background-color: #fff;
    position: relative;
    overflow: hidden;
}

.comm-close {
    position: absolute;
    top: 0;
    right: 0;
    cursor: pointer;
}

.comm-chedel {
    width: 26px;
    height: 26px;
    position: absolute;
    top: 8px;
    left: 8px;
    z-index: 3;
}

.comm-wavs {
    width: 100%;
    border-radius: 8px;
    display: flex;
    align-items: center;
    background-color: rgba(56, 123, 255, 0.1);
}
</style>